package com.github.codemperor.core.message.omnisend;

import com.alibaba.fastjson.JSONObject;
import com.github.codemperor.core.message.dingtalk.robot.RobotMsgSend;
import com.github.codemperor.core.message.omnisend.bean.RestErrorException;
import com.github.codemperor.core.message.omnisend.bean.order.ContactsPostRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class OmniSendClient {
    private static Logger log = LoggerFactory.getLogger(OmniSendClient.class);
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String host = "https://api.omnisend.com/v3/";
    private final String omnKey = "";
    private Object requestParams;

    private HttpEntity<Object> requestEntity() {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("X-API-KEY", omnKey);
        requestHeaders.add("Content-Type", "application/json");
        return new HttpEntity<>(requestParams, requestHeaders);
    }

    // 获取omnisend相关的日期格式化类，带时区
    public static SimpleDateFormat sdfZone() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        return sdf;
    }

    public static OmniSendClient build() {
        return new OmniSendClient();
    }

    /**
     * 初始化event
     *
     * @param eventId
     * @return
     */
    public OmniSendClient event(String eventId) {
        this.host = this.host + "events/" + eventId;
        return this;
    }

    /**
     * 初始化order
     *
     * @param orderNo 只取第一个参数作为orderNo，可不传
     * @return
     */
    public OmniSendClient order(String... orderNo) {
        if (orderNo == null || orderNo.length <= 0) {
            this.host = this.host + "orders";
        } else {
            this.host = this.host + "orders/" + orderNo[0];
        }

        return this;
    }

    /**
     * 设置params
     *
     * @param params
     * @return
     */
    public OmniSendClient params(Object params) {
        this.requestParams = params;
        return this;
    }

    /**
     * post
     *
     * @return
     */
    public Object post() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new RestErrorException());
        return restTemplate.postForEntity(host, requestEntity(), Object.class);
    }

    /**
     * PATCH
     *
     * @return
     */
    public Object patch() {
        // springboot自带实现的RestTemplate不支持patch方法，使用http clinet实现
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(10000);
        factory.setReadTimeout(10000);
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new RestErrorException()); //转化错误处理
        return restTemplate.patchForObject(host, requestEntity(), Object.class);
    }

    /**
     * get
     *
     * @return
     */
    public Object get() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new RestErrorException());
        return restTemplate.exchange(host, HttpMethod.GET, requestEntity(), Object.class);
    }


    public Object contactAddOrUpdate(ContactsPostRequest user) {
        this.host = this.host + "contacts";
        String hostCopy = this.host;

        //先update
        this.host = this.host + "?email=" + user.getEmail();
        ContactsPostRequest updateReq = new ContactsPostRequest();
        updateReq.setFirstName(user.getFirstName());
        updateReq.setLastName(user.getLastName());
        this.params(updateReq);
        Object res = this.patch();
        JSONObject ob = JSONObject.parseObject(JSONObject.toJSONString(res));

        //如果用户不存在，insert
        if (ob != null && ob.get("error") != null && ob.get("error").toString().contains("Contact not found")) { //add
            this.host = hostCopy;
            this.params(user);
            res = this.post();
        }
        return res;
    }

    //创建订单的信息返回处理
    public static JSONObject omnisendNewOrderResHandler(Object res, String title, String description) {
        // 加监控和机器人
        JSONObject ob = JSONObject.parseObject(JSONObject.toJSONString(res));
        int code = (Integer) ob.get("statusCodeValue");
        if (code != 200) {
            log.error("[omnisendNewOrderResHandler error] error: {}", ob.toJSONString());
            List<String> msg = new ArrayList<>();
            msg.add("**" + title + "**");
            msg.add(description);
            msg.add(ob.toJSONString());
            msg.add("> by: " + sdf.format(new Date()));
            RobotMsgSend.sendDingtalkRobotMarkdownMsg(title, msg, false);
        } else {
            log.info("[omnisendNewOrderResHandler {}] res: {}", description, ob.toJSONString());
        }

        return ob;
    }

    //events邮件返回值处理
    public static JSONObject omnisendEmailResHandler(Object res, String title, String description) {
        JSONObject ob = JSONObject.parseObject(JSONObject.toJSONString(res));
        if (ob != null && ob.get("error") != null) {
            log.error("[OmnisendEventsEmailResHandler error] error: {}", ob.toJSONString());
            List<String> msg = new ArrayList<>();
            msg.add("**" + title + "**");
            msg.add(description);
            msg.add(ob.toJSONString());
            msg.add("> by: " + sdf.format(new Date()));
            RobotMsgSend.sendDingtalkRobotMarkdownMsg(title, msg, false);
        } else {
            log.info("[OmnisendEventsEmailResHandler {}] res: {}", description, ob == null ? "NULL" : ob.toJSONString());
        }
        return ob;
    }

    public static void main(String[] args) {
        // Monthly Protection
        StringBuffer sb = new StringBuffer();
        sb.append("<a href='");
        //sb.append(websiteHost + "/account/reset-password/" + token + "?uptradeemail=" + email);  //这里是连接
        sb.append("' target='_blank'>Pay</a>");

        JSONObject fields = new JSONObject();
        fields.put("TokenizedURL", sb.toString());
        JSONObject params = new JSONObject();
        params.put("email", "");//todo 这里是接收邮件的email
        params.put("fields", fields);
        Object res = OmniSendClient.build().order("5dea5dba99f0b741e7339324").params(params).patch();
        System.out.println(JSONObject.toJSONString(res));

    }
}
